import axios from 'axios'
import router from '@/router'
import { Toast } from 'vant'

// application/x-www-form-urlencoded;charset=UTF-8
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.timeout = 60000

let loading
//内存中正在请求的数量
let loadingNum = 0

function startLoading() {
  if (loadingNum == 0) {
    loading = Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
    })
  }
  //请求数量加1
  loadingNum++
}

function endLoading() {
  if (loadingNum <= 0) return
  //请求数量减1
  loadingNum--
  if (loadingNum == 0 && loading) {
    loading.clear()
    loading = null
  }
}

function randomString(len) {
  len = len || 32
  var charsAll = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = charsAll.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += charsAll.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

axios.interceptors.request.use(
  config => {
    let ctimestamp = parseInt(Date.now() / 1000) // 时间戳
    let cnonce = randomString(6)
    let papams = 'params'
    if ((config.data || config.params) instanceof Object && Object.keys(config.data || config.params).length > 0) {
      papams = Object.values(config.data || config.params)[0]
    }
    var sm3 = require('sm-crypto').sm3
    let cData = `${papams}-POST-${ctimestamp}-${cnonce}`
    let csign = sm3(cData)

    config.headers.ctimestamp = ctimestamp
    config.headers.cnonce = cnonce
    config.headers.csign = csign

    //请求拦截器
    config.headers.appCode = 'jx-clivil-servant-assessment'
    config.headers.userId = localStorage.userId
    config.headers.token = localStorage.token
    config.headers.userName = encodeURIComponent(sessionStorage.userName)
    config.headers.organId = localStorage.userInfo ? JSON.parse(localStorage.userInfo).loginPostInfo.orgId : ''

    config.headers.type = '1'
    // 租户ID
    config.headers.tenantId = localStorage.userInfo ? JSON.parse(localStorage.userInfo).tenantId : ''
    if (!config.headers.hideLoading) {
      startLoading()
    }
    // 执行下载文件时，后台返回blob，需要设置responseType类型
    config.responseType = sessionStorage.responseType ? 'blob' : ''
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    endLoading()
    if (!sessionStorage.responseType) {
      if (response.data.status == 401) {
        if (!['flutter-android', 'flutter-ios', 'flutter'].includes(localStorage.platform)) {
          localStorage.clear()
          sessionStorage.clear()
          router.push('/login')
        } else {
          localStorage.clear()
          sessionStorage.clear()
          window.flutter_inappwebview.callHandler('logOut', '')
        }
        return response
      }
      if ((response.data.status && response.data.status !== 200) || response.data.code === 1) {
        const messageData = response.data.message || response.data.msg
        if (/[\u4E00-\u9FA5]+/.test(messageData)) {
          Toast.fail({
            message: `${messageData}`,
          })
        } else {
          Toast.fail({
            message: `${response.data.status}操作失败，请联系管理员`,
          })
        }
      }
    }
    return response
  },
  err => {
    console.log(err.message, 'errerr')
    endLoading()
    if (err.message == 'timeout of 60000ms exceeded') {
      Toast.fail({
        message: `请求超时，请重试`,
      })
      return Promise.reject(err.message)
    }
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '请求错误(400)'
          break
        case '401':
          if (!['flutter-android', 'flutter-ios', 'flutter'].includes(localStorage.platform)) {
            localStorage.clear()
            sessionStorage.clear()
            router.push('/login')
          } else {
            localStorage.clear()
            sessionStorage.clear()
            window.flutter_inappwebview.callHandler('logOut', '')
          }

          break
        case 403:
          err.message = '拒绝访问(403)'
          break
        case 404:
          err.message = '请求出错(404)'
          break
        case 408:
          err.message = '请求超时(408)'
          break
        case 500:
          err.message = '服务器错误(500)'
          break
        case 501:
          err.message = '服务未实现(501)'
          break
        case 502:
          err.message = '网络错误(502)'
          break
        case 503:
          err.message = '服务不可用(503)'
          break
        case 504:
          err.message = '网络超时(504)'
          break
        case 505:
          err.message = 'HTTP版本不受支持(505)'
          break
        default:
          err.message = `连接出错(${err.response.status})!`
      }
    } else {
      err.message = '连接服务器失败!'
    }
    if (/[\u4E00-\u9FA5]+/.test(err.response.data.message)) {
      Toast.fail({
        message: `${err.data.message}`,
      })
    } else {
      Toast.fail({
        message: `${err.data.status || err.response.data.status}操作失败，请联系管理员`,
      })
    }
    return Promise.reject(err.message)
  }
)
// axios.interceptors.response.use(response => {//响应拦截器
//     endLoading();
//     return response.data
// },error => {
//     return Promise.reject(error.response);;
// });
export const get = (url, params) => {
  return axios
    .get(url, {
      params,
    })
    .then(res => {
      return res.data
    })
}

export const post = (url, params, config = {}) => {
  return axios
    .post(url, params, {
      ...config,
    })
    .then(res => {
      return res.data
    })
}
